package day11.handler.simpleChannelHandler.request;

import day11.packet.request.CreateGroupRequestPacket;
import day11.packet.response.CreateGroupResponsePacket;
import day11.util.IDUtil;
import day11.util.session.GroupSession;
import day11.util.session.Session;
import day11.util.session.SessionUtil;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.DefaultChannelGroup;

import java.util.ArrayList;
import java.util.List;

/**
 * @author chenshijie
 * @date 2024/1/1 15:28
 */

public class CreateGroupRequestHandler extends SimpleChannelInboundHandler<CreateGroupRequestPacket> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, CreateGroupRequestPacket createGroupRequestPacket) throws Exception {

        List<Integer> userIdsList = createGroupRequestPacket.getUserIdsList();
        Session groupBosssession = SessionUtil.getSession(ctx.channel());
        int groupBossUserId = groupBosssession.getUserId();

        if (!userIdsList.contains(groupBossUserId)) {
            userIdsList.add(groupBossUserId);
        }
        List<Session> userSessions = new ArrayList<>();

        // 1. 创建一个channel分组
        DefaultChannelGroup channelGroup = new DefaultChannelGroup(ctx.executor());

        // 2. 筛选出待加入群聊的用户的channel和userName
        ArrayList<String> userNameList = new ArrayList<>();
        for (Integer userId : userIdsList) {
            Channel channel = SessionUtil.getChannel(userId);
            Session session = SessionUtil.getSession(channel);
            if (channel != null) {
                userSessions.add(session);
                channelGroup.add(channel);
                userNameList.add(session.getUserName());
            }
        }

        // 3. 创建群聊创建结果的响应
        CreateGroupResponsePacket createGroupResponsePacket = new CreateGroupResponsePacket();
        createGroupResponsePacket.setSuccess();
        createGroupResponsePacket.setGroupId(IDUtil.randomNumber());
        createGroupResponsePacket.setUserNameList(userNameList);

        // 4. 创建群标识
        GroupSession groupSession = new GroupSession();
        int groupId = createGroupResponsePacket.getGroupId();
        groupSession.setGroupId(groupId);
        groupSession.setUserSessions(userSessions);
        groupSession.setChannelGroup(channelGroup);
        SessionUtil.bindGroupSession(groupId, groupSession);

        // 5. 给每个客户端都发送拉群通知
        channelGroup.writeAndFlush(createGroupResponsePacket);
        System.out.println("群创建成功，群id为【" + createGroupResponsePacket.getGroupId() + "】");
        System.out.println("群里面有: " + createGroupResponsePacket.getUserNameList());

    }

}
